#!/bin/sh

#New Problem Wizard

to_upper()
{
	echo $1 | tr  "[:lower:]" "[:upper:]"
}

to_lower()
{
	echo $1 | tr  "[:upper:]" "[:lower:]"
}

capitalize()
{
	for i in $1
	do
		CAP=`echo -n "${i:0:1}" | tr "[:lower:]" "[:upper:]"`
		echo -n "${CAP}${i:1}"
	done
}

name="$@"

if [ -z "$name" ]
then
	echo "enter problem name: "
	read name

	if [ -z "$name" ]
	then
		echo "Usage: wizard.sh ProblemName"
		exit
	fi
fi

is_valid_name=`expr match "$name" '^[a-zA-Z_][a-zA-Z0-9_]*$'`
if [ "$is_valid_name" == "0" ]
then
	echo "ERROR: bad ProblemName"
	exit
fi

cap_name=`capitalize "$name"`
up_name=`to_upper "$name"`
lo_name=`to_lower "$name"`

#current working directory
work_dir=~+

new_dir="$work_dir/$lo_name"
gen_dir="$work_dir/generic"

if [ -d "$new_dir" ]
then
	echo "ERROR: folder '$lo_name' already exist"
	exit
fi

if [ ! -d "$gen_dir" ]
then
	echo "ERROR: 'generic' folder not found"
	exit
fi

process_file()
{
#	echo "file: $1"

	cur_name=${1##*/}
	cur_dir=$2
	new_name=${cur_name/generic/"$lo_name"}

	ext=${1##*.}
	ext=`to_lower "$ext"`
	if [ "$ext" = "cpp" ] || [ "$ext" = "h" ] || [ "$ext" = "ini" ] || [ "$ext" = "sh" ] || [ "$ext" = "cmd" ] || [ "$ext" = "vcproj" ] || [ "$cur_name" = "Makefile" ]
	then
		if sed -e "s/generic/$lo_name/g" -e "s/Generic/$cap_name/g" -e "s/GENERIC/$up_name/g" $1 > "$cur_dir/$new_name"
		then
			if [ "$ext" = "sh" ]
			then
				chmod +x "$cur_dir/$new_name"
			fi
			echo "$cur_dir/$new_name"
		else
			echo "ERROR: unable to copy generic file(s)"
			exit
		fi
	fi
}

do_recursive()
{
	echo "$2"
	if ! mkdir "$2"
	then
		echo "ERROR: unable to create directory '$2'"
		exit
	fi

	for f in $1/*
	do
		cur_name=${f##*/}
		sub_dir="$2/$cur_name"
		if [ -d "$f" ]
		then
			lo_cur_name=`to_lower "$cur_name"`
			if [ "$lo_cur_name" != ".svn" ] && [ "$lo_cur_name !=_svn" ]
			then
				do_recursive "$f" "$sub_dir"
			fi
		else
			process_file "$f" "$2"
		fi
	done
}


do_recursive "$gen_dir" "$new_dir"
cd ..
work_dir=~+
problem_dir="$work_dir/problems/$lo_name"
mkdir -p "$problem_dir"
cd "$work_dir/$projects"

echo "Project '$name' created successfully."
echo "Please copy problem instances to '$problem_dir'"

#eof
